﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Agents.Admin
{
    public partial class NewStockOrder : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void dgProducts_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Redirects the admin back to his homepage when the "back" button is pressed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void backBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminMenu.aspx");
        }

        /// <summary>
        /// Perform the order.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void okBtn_Click(object sender, EventArgs e)
        {
            // Disable the buttons so the user can't interfere
            backBtn.Enabled = false;
            okBtn.Enabled = false;

            // Get all the products with number of items bigger than 0
            int numItems, productId;
            Dictionary<int, int> numItemsPerProduct = new Dictionary<int, int>();

            foreach (DataGridItem item in dgProducts.Items)
            {
                productId = Int32.Parse(item.Cells[0].Text);
                numItems = 0;
                Int32.TryParse(((System.Web.UI.WebControls.TextBox)(
                    item.Cells[3].Controls[1])).Text, out numItems);

                if (numItems > 0)
                {
                    numItemsPerProduct.Add(productId, numItems);
                }
            }

            // Save the stock order
            Queries queries = new Queries();
            int stockOrderId = queries.AddNewStockOrder(
                DateTime.Now, numItemsPerProduct, Convert.ToDouble(txtSum.Text));

            // Announce success and wait for 2 seconds before redirecting
            lblMessage.Text = String.Format(
                "הזמנת מלאי מספר {0} בוצעה בהצלחה. ניתן לצפות בה ממסך הזמנות מלאי",
                stockOrderId);
            redirectionTimer.Enabled = true;
        }

        /// <summary>
        /// Redirect back to the admin menu after a few seconds
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void redirectionTimer_Tick(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminMenu.aspx");
        }
    }
}